const axios = require("axios");
const jwt = require("jsonwebtoken");
const db = require("../db");
const { wx, jwtSecret, jwtExpire } = require("../config");

async function loginByWeChat(ctx) {
  const { code, nickname = "", avatarUrl = "" } = ctx.request.body;
  console.log(code,'code/');
  if (!code) {
    ctx.body = { code: 400, message: "code不能为空" };
    return;
  }

  // 1. 用 code 获取 openid 和 session_key
  const wxUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=${wx.appid}&secret=${wx.secret}&js_code=${code}&grant_type=authorization_code`;

  const wxRes = await axios.get(wxUrl);
  console.log(wxRes.data, "wxRes",wxUrl);

  const { openid, session_key, errcode, errmsg } = wxRes.data;

  if (!openid) {
    ctx.body = { code: 500, message: "微信登录失败", errcode, errmsg };
    return;
  }

  // 2. 查询或注册用户
  const [rows] = await db.query(`SELECT * FROM users WHERE wechat_openid = ?`, [
    openid,
  ]);

  let user;
  if (rows.length > 0) {
    user = rows[0];
  } else {
    const [result] = await db.query(
      `INSERT INTO users (wechat_openid, nickname, avatar_url) VALUES (?, ?, ?)`,
      [openid, nickname, avatarUrl]
    );
    user = {
      id: result.insertId,
      wechat_openid: openid,
      nickname,
      avatar_url: avatarUrl,
    };
  }

  // 3. 签发 token
  const token = jwt.sign({ userId: user.id }, jwtSecret, {
    expiresIn: jwtExpire,
  });

  ctx.body = {
    code: 200,
    message: "登录成功",
    data: {
      token,
      user,
    },
  };
}

// 手机号注册
async function registerByPhone(ctx) {
  const { phone } = ctx.request.body;

  if (!phone || !/^1\d{10}$/.test(phone)) {
    ctx.body = { code: 400, message: "手机号格式错误" };
    return;
  }

  const [rows] = await db.query(`SELECT * FROM users WHERE phone = ?`, [phone]);

  if (rows.length > 0) {
    ctx.body = { code: 409, message: "手机号已注册" };
    return;
  }

  const [result] = await db.query(`INSERT INTO users (phone) VALUES (?)`, [
    phone,
  ]);

  ctx.body = {
    code: 200,
    message: "注册成功",
    data: { userId: result.insertId, phone },
  };
}

// 微信小程序一键注册
async function registerByWeChat(ctx) {
  const { openid, nickname, avatarUrl } = ctx.request.body;

  if (!openid) {
    ctx.body = { code: 400, message: "openid 必填" };
    return;
  }

  const [rows] = await db.query(`SELECT * FROM users WHERE wechat_openid = ?`, [
    openid,
  ]);

  if (rows.length > 0) {
    ctx.body = { code: 200, message: "用户已存在", data: rows[0] };
    return;
  }

  const [result] = await db.query(
    `INSERT INTO users (wechat_openid, nickname, avatar_url) VALUES (?, ?, ?)`,
    [openid, nickname || "", avatarUrl || ""]
  );

  ctx.body = {
    code: 200,
    message: "微信注册成功",
    data: { userId: result.insertId },
  };
}

module.exports = {
  registerByPhone,
  registerByWeChat,
  loginByWeChat,
};
